import { users, verificationCodes } from '../../database/schema';
import { hashPassword } from '../../utils/auth';
import {gt} from 'drizzle-orm'

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { email, code, newPassword } = body;

  const db = useDrizzle()

  // 验证重置码
  const verification = await db.select()
    .from(verificationCodes)
    .where(
      and(
        eq(verificationCodes.email, email),
        eq(verificationCodes.code, code),
        eq(verificationCodes.type, 'reset'),
        gt(verificationCodes.expiresAt, new Date())
      )
    )
    .limit(1);

  if (!verification.length || verification[0].used) {
    throw createError({ statusCode: 400, message: 'Invalid reset code' });
  }

  // 更新密码
  const passwordHash = await hashPassword(newPassword);
  await db.update(users)
    .set({ passwordHash })
    .where(eq(users.email, email));

  // 标记验证码已使用
  await db.update(verificationCodes)
    .set({ used: true })
    .where(eq(verificationCodes.id, verification[0].id));

  return { success: true };
});